<template>
  <div>
    <div v-if="loading">正在加载评论...</div>
    <div v-else-if="error">加载评论失败: {{ error }}</div>
    <div v-else-if="comments && comments.length">
      <el-table :data="comments">
        <el-table-column prop="reader.username" label="用户" width="120" />
        <el-table-column prop="content" label="内容" />
        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <el-button size="small" type="danger" @click="deleteComment(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-else>该小说暂无评论</div>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ADMIN_API } from '@/utils/api'

const props = defineProps({
  novelId: {
    type: [String, Number],
    required: true
  }
})

const comments = ref([])
const loading = ref(false)
const error = ref(null)

const fetchComments = async () => {
  if (!props.novelId) return
  loading.value = true
  error.value = null
  try {
    comments.value = await request.get(`${ADMIN_API}/novels/${props.novelId}/comments`)
  } catch (err) {
    error.value = err
  } finally {
    loading.value = false
  }
}

const deleteComment = async (comment) => {
  ElMessageBox.confirm('确定要删除这条评论吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await request.delete(`${ADMIN_API}/comments/${comment.comment_id}`)
      ElMessage.success('评论删除成功')
      fetchComments() // 重新加载评论
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

watch(() => props.novelId, fetchComments, { immediate: true })

</script>

<style scoped>
</style>